import { useState, useEffect } from 'react';
import { Card, DatePicker } from 'antd';
import { Column } from '@ant-design/plots';
import { getOrderList } from './service';
import moment from 'moment';
interface orderType {
  id: number;
  count: number;
  created_at: Date;
  year: number;
  month: number;
  day: number;
  pay_amount: number;
  status: string;
  user_id: number;
}
const ECharts = () => {
  const [data, setData] = useState<any[]>([]);
  const [curYear, setCurYear] = useState(moment().format('YYYY'));
  const fetchData = async () => {
    try {
      const res = await getOrderList({
        page: 1,
        pageSize: 100,
        year: curYear,
      });
      if (res.success) {
        const arr: { type: string; sales: number }[] = [];
        res.data.list.map((cur: orderType) => {
          const tempSales = arr[cur.month - 1]?.sales || 0;
          arr[cur.month - 1] = {
            type: cur.month + '月',
            sales: tempSales + cur.pay_amount,
          };
        });
        setData(arr);
        return true;
      } else {
        return false;
      }
    } catch (error) {
      return false;
    }
  };

  useEffect(() => {
    fetchData();
  }, [curYear]);
  const config = {
    data,
    xField: 'type',
    yField: 'sales',
    label: {
      // 可手动配置 label 数据标签位置
      position: 'middle',
      // 'top', 'bottom', 'middle',
      // 配置样式
      style: {
        fill: '#FFFFFF',
        opacity: 0.6,
      },
    },
    xAxis: {
      label: {
        autoHide: true,
        autoRotate: false,
      },
    },
    meta: {
      type: {
        alias: '月份',
      },
      sales: {
        alias: '销售额',
      },
    },
  };

  return (
    <Card
      title="当年销售统计柱状图"
      extra={
        <DatePicker
          onChange={(val) => {
            if (val) {
              setCurYear(moment(val).format('YYYY'));
            } else {
              setCurYear(moment().format('YYYY'));
            }
          }}
          picker="year"
        />
      }
    >
      <Column {...config} />
    </Card>
  );
};
export default ECharts;
